package com.bankcomm.util;

/**
 * 将汉字转化为拼音，并获取首字母
 * @author cheng.l 2013-6-17 下午06:52:06
 */
public class PinyinUtils {
	private static final char[] alphatable = { 'A', 'B', 'C', 'D', 'E', 'F',
		'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
		'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
	
	private static final int[] table = new int[] { 45217, 45253, 45761, 46318,
		46826, 47010, 47297, 47614, 47614, 48119, 49062, 49324, 49896,
		50371, 50614, 50622, 50906, 51387, 51446, 52218, 52218, 52218,
		52698, 52980, 53689, 54481, 55289 };
	
	/**
	 * 得到中文拼音首字母
	 * @param str
	 * @return
	 */
	public static String getFirtChar(String str) {
		// 多音字城市预先处理
		String[] specialCity = {"重庆", "石家庄", "长沙", "长治", "长春", "乐山", "乐清", "西藏"};
		String[] specialPY = {"C", "S", "C", "C", "C", "L", "L", "X"};
		int slen = specialCity.length;
		for(int t = 0; t < slen; t++){
			if(str.equals(specialCity[t])){
				return specialPY[t];
			}
		}
		
		String temp = null;
		temp = String2Alpha(str);
		if(null != temp){
			temp = String.valueOf(temp.charAt(0));
		}
		return temp;
	}
	
	/**
	 * 将Char转换成
	 */
	public static char Char2Alpha(char ch) {
		if (ch >= 'a' && ch <= 'z')
			return (char) (ch - 'a' + 'A');
		if (ch >= 'A' && ch <= 'Z')
			return ch;
		int gb = gbValue(ch);
		if (gb < table[0])
			return '*';
		for (int i = 0; i < 26; ++i) {
			if (match(i, gb)) {
				if (i >= 26)
					return '*';
				else
					return alphatable[i];
			}
		}
		return '*';
	}

	/**
	 * 将拼音取第一个字母
	 */
	public static String String2Alpha(String str) {
		String Result = "";
		try {
			for (int i = 0; i < str.length(); i++) {
				Result += Char2Alpha(str.charAt(i));
			}
		} catch (Exception e) {
			Result = " ";
		}
		if (null != Result && !"".equalsIgnoreCase(Result)) {
			Result = Result.substring(0, 1);
		}
		return Result;
	}

	/**
	 * 比对
	 */
	private static boolean match(int i, int gb) {
		if (gb < table[i])
			return false;
		int j = i + 1;
		while (j < 26 && (table[j] == table[i]))
			++j;
		if (j == 26)
			return gb <= table[j];
		else
			return gb < table[j];
	}

	/**
	 * 得到GBK的编码值
	 */
	private static int gbValue(char ch) {
		String str = new String();
		str += ch;
		try {
			byte[] bytes = str.getBytes("GB2312");
			if (bytes.length < 2)
				return 0;
			return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff);
		} catch (Exception e) {
			return '*';
		}
	}
}
